package com.itany.shop.factory;


import com.itany.shop.exception.ObjectNotFoundException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class ObjectFactory {

    private static Map<String, Object> objs;

    static {
        objs = new HashMap<>();
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            ObjectFactory.class
                                    .getClassLoader()
                                    .getResourceAsStream("beans.properties")));
            String line = null;
            while ((line = br.readLine()) != null) {
                if (!"".equals(line) && !line.startsWith("#")) {
                    // 读取到每一行的数据之后,根据等号分隔
                    String[] arr = line.split("=");
                    String key = arr[0];
                    // 此时的value并不是一个对象,而是一个包含了包名.类名的字符串
                    String value = arr[1];
//                    System.out.println(value);
                    // 根据value的包名.类名通过反射生成该value值所表示的对象
                    Class c = Class.forName(value);
                    Object object = c.newInstance();
                    // 将key与object存储到Map集合中
                    objs.put(key, object);
                }
            }
//            System.out.println(objs);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        }
    }


    public static Object getObject(String key) {
        Object obj = objs.get(key);
        if (obj == null) {
            throw new ObjectNotFoundException("根据指定的key:" + key + "没有找到对应的配置");
        }
        return obj;
    }
}
